/*
 * Javlov - a Java toolkit for reinforcement learning with multi-agent support.
 * 
 * Copyright (c) 2009 Matthijs Snel
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package net.javlov;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jdom.Element;

import net.javlov.util.ObjectFactory;
import net.javlov.util.SAXReader;

public class XMLAgentBuilder {
	
	private List<Agent> agents;
	//TODO doesn't having a single factory defy the purpose of the XML config?
	private PolicyFactory polFactory;
	private Iterator<Agent> agentItr;
	
	public Agent buildAgent() {
		if ( agentItr.hasNext() )
			return agentItr.next();
		return null;
	}
	
	public void load(String configFile) {
		//TODO handle null case
		Element root = SAXReader.read(configFile).getRootElement();
		loadAgents(root.getChildren("agent"));
		agentItr = agents.iterator();
	}
	
	public void setPolicyFactory(PolicyFactory pf) {
		polFactory = pf;
	}
	
	private void loadAgents(List<Element> agentEls) {
		agents = new ArrayList<Agent>();
		Agent a;
		Element javaClass;
		int number;
		for ( Element el : agentEls ) {
			number = Integer.parseInt(el.getAttributeValue("number"));
			javaClass = el.getChild("javaclass");
			for ( int i = 0; i < number; i++ ) {
				a = (Agent) ObjectFactory.createObject(javaClass);
				if ( polFactory != null )
					a.setPolicy(polFactory.create());
				agents.add(a);
			}
		}
	}
}
